<template>
    <!-- 个人加班 --->
    <div>
        <Dialog
                ref="d1"
                dialogCls="mydlgg"
                headerCls="mydlgg-head"
                footerCls="mydlgg-foot"
                :dialogStyle="{ width: '550px' }"
                :modal="true"
                borderType="thin"
        >
            <div slot="header">
                <span class="headerIcon newlyAdded"></span>
                <span class="titleStyle">加班</span>
            </div>

            <div class="insidePadding">
                <div class="upContent" style="height:auto">


                    <div style="flex:1;">
                        <div>
                            <fieldset class="fieldsetStyle">
                                <fieldset
                                class="fieldsetStyle"
                                        style="height:200px"
                                >
                                    <legend>
                                        <b style="color:#293569">选择日期范围</b>
                                    </legend>

                                    <div class="fleft">
                                        <Label for="DateBox5">加班日期</Label>
                                        <DateBox
                                                id="DateBox5"
                                                inputId="DateBox5"
                                                format="yyyy-MM-dd"
                                                v-model="dateScope.otDate"
                                                @valueChange="selectionChangeOverTime"
                                                :editable="false"
                                                :validator="otDateValidator"
                                        />
                                    </div>
                                    <div class="fenGeXian"></div>
                                    <div style="line-height: 20px;display: flex;align-items:center;">
                                        <label class="textbox-label" for="sj">手动设置</label>
                                        <RadioButton
                                                inputId="sj"
                                                class="rs_15"
                                                name="groupTime"
                                                value="1"
                                                v-model="timeSelectPattern"
                                        ></RadioButton>
                                        <label class="textbox-label" for="banCi">按班次设置</label>
                                        <RadioButton

                                                inputId="banCi"
                                                class="rs_15"
                                                name="groupTime"
                                                value="2"
                                                v-model="timeSelectPattern"
                                        ></RadioButton>
                                    </div>
                                    <div class="fenGeXian"></div>
                                    <div style="width: 100%" v-show="banciSelectFlag">
                                        <div class="fleft">
                                            <Label>选择班次</Label>
                                            <ComboBox
                                                    :disabled="timeFlag"
                                                    ref="selectBanCi"
                                                    valueField="id"
                                                    textField="name"
                                                    v-model="dateScope.banCiType"
                                                    :virtualScroll="true"
                                                    :data="dateScope.banCiTypeData"
                                                    :panelStyle="panelStyle3"
                                                    @selectionChange="selectionChangeBanCi"
                                            ></ComboBox>
                                        </div>
                                    </div>
                                    <div class="fleft" v-show="timeFlag">
                                        <Label for="DateBox2">开始时间</Label>
                                        <DateBox
                                                :disabled="banciSelectFlag"
                                                inputId="DateBox2"
                                                format="yyyy-MM-dd"
                                                v-model="dateScope.startDate"
                                                :validator="validator"
                                                :editable="false"
                                        />
                                    </div>
                                    <div class="fleft" v-show="timeFlag">
                                        <Label></Label>
                                        <NumberBox
                                                :disabled="banciSelectFlag"
                                                :min="0"
                                                :max="23"
                                                :spinners="true"
                                                style="width:60px"
                                                v-model="dateScope.beginHour"
                                                :prefix="dateScope.beginHour < 10 ? '0' : ''"
                                        ></NumberBox>
                                        <span class="inputStyle">时</span>
                                        <ComboBox
                                                :disabled="banciSelectFlag"
                                                valueField="id"
                                                textField="name"
                                                :style="{ width: '60px' }"
                                                v-model="dateScope.beginMinute"
                                                :virtualScroll="true"
                                                :data="[
                                                  { id: '00', name: '00' },
                                                  { id: '15', name: '15' },
                                                  { id: '30', name: '30' },
                                                  { id: '45', name: '45' }
                                                ]"
                                                :panelStyle="panelStyle3"
                                        ></ComboBox>
                                        <span class="inputStyle">分</span>
                                        <!-- <NumberBox
                                                            :min="0"
                                                            :max="59"
                                                            :spinners="true"
                                                            style="width:60px"
                                                            v-model="dateScope.beginMinute"
                                                            :prefix="dateScope.beginMinute < 10 ? '0' : ''"
                                                          ></NumberBox> -->
                                    </div>
                                    <div class="fleft" v-show="timeFlag">
                                        <Label for="DateBox3">结束时间</Label>
                                        <DateBox
                                                :disabled="banciSelectFlag"
                                                :readonly="false"
                                                inputId="DateBox3"
                                                format="yyyy-MM-dd"
                                                v-model="dateScope.endDate"
                                                :validator="validator"
                                                :editable="false"
                                        />
                                    </div>
                                    <div class="fleft" v-show="timeFlag">
                                        <Label></Label>
                                        <NumberBox
                                                :disabled="banciSelectFlag"
                                                :min="0"
                                                :max="23"
                                                :spinners="true"
                                                style="width:60px"
                                                v-model="dateScope.endHour"
                                                :prefix="dateScope.endHour < 10 ? '0' : ''"
                                        ></NumberBox>
                                        <span class="inputStyle">时</span>
                                        <ComboBox
                                                :disabled="banciSelectFlag"
                                                valueField="id"
                                                textField="name"
                                                :style="{ width: '60px' }"
                                                v-model="dateScope.endMinute"
                                                :virtualScroll="true"
                                                :data="[
                                                  { id: '00', name: '00' },
                                                  { id: '15', name: '15' },
                                                  { id: '30', name: '30' },
                                                  { id: '45', name: '45' }
                                                ]"
                                                :panelStyle="panelStyle3"
                                        ></ComboBox>
                                        <span class="inputStyle">分</span>
                                        <!-- <NumberBox
                                                            :min="0"
                                                            :max="59"
                                                            :spinners="true"
                                                            style="width:60px"
                                                            v-model="dateScope.endMinute"
                                                            :prefix="dateScope.endMinute < 10 ? '0' : ''"
                                                          ></NumberBox> -->
                                    </div>
                                </fieldset>
                                <fieldset
                                class="fieldsetStyle"
                                        style="height:80px;margin-bottom:10px;"
                                >
                                    <legend>
                                        <b style="color:red">*</b>
                                        <b style="color:#293569">事由</b>
                                    </legend>
                                    <!-- fieldset、legend如果需要带边框加标题的容器这俩标签必须保留 -->
                                    <TextBox
                                            :multiline="true"
                                            v-model="dateScope.reason"
                                            style="width:100%;height:50px"
                                            placeholder="请填写加班事由（必填）"
                                    ></TextBox>
                                </fieldset>
                                <fieldset
                                        class="fieldsetStyle"
                                        style="height:104px;"
                                >
                                    <legend>
                                        <b style="color:#293569">上传附件</b>
                                    </legend>
                                    <upload-file ref="upload1"/>
                                    <upload-file ref="upload2"/>
                                    <upload-file ref="upload3"/>
                                </fieldset>

                            </fieldset>
                        </div>
                    </div>

                </div>
            </div>

            <div slot="footer" style="border:none">
                <div class="footerDiv">
                    <!-- footer、footerDiv这两个div必须保留 -->
                    <LinkButton @click="submitOverTime" class="saveBtn">保存</LinkButton>
                    <span style="margin:0px 10px;"/>
                    <LinkButton @click="close" class="cancelBtn">返回</LinkButton>
                </div>
            </div>
        </Dialog>

        <!--请假错误详情-->
        <Dialog
                ref="errorXq"
                dialogCls="mydlgg"
                headerCls="mydlgg-head"
                footerCls="mydlgg-foot"
                :dialogStyle="{ width: '720px' }"
                :modal="true"
                borderType="thin"
        >
            <div slot="header">
                <span class="headerIcon newlyAdded"></span>
                <span class="titleStyle">加班错误详情</span>
            </div>
            <div class="insidePadding">
                <!-- 这个div必须保留 -->
                <fieldset class="fieldsetStyle">
                    <!-- 表格容器   -->
                    <div style="height: 450px">
                        <ag-grid-vue
                                style="width: 100%; height: 100%;"
                                class="ag-theme-balham"
                                :rowData="err.xqRowData"
                                :columnDefs="err.xqColumnDefs"
                        ></ag-grid-vue>
                    </div>
                </fieldset>
            </div>
        </Dialog>
    </div>
</template>

<script>
    import userApi from "@/api/user";
    import itemApi from "@/api/sys/item";
    import scheduleApi from "@/api/schedule/schedule";
    import overTimeApi from "@/api/overTime/overTime";
    import timeIntervalApi from "@/api/timeInterval/timeInterval";
    import sidebarDept from "@/components/dept/sidebarDept";
    import {tableBoxHeight} from "@/api/communal";
    import {AgGridVue} from "ag-grid-vue";
    import dateUtil from "@/utils/dateUtils";
    import moment from "moment";
    import UploadFile from "@/components/uploadFile";
    import selectApprover from "@/components/selectApprover";

    export default {
        props: {
            parentSearch: Function,
            peopleData: Array
        },
        components: {
            sidebarDept,
            AgGridVue,
            UploadFile,
            selectApprover
        },
        name: "",
        data() {
            return {
                panelStyle2: {
                    height: "auto"
                },
                panelStyle: {
                    height: "100px",
                    borderWidth: "1px",
                    borderColor: "#ccc",
                    borderStyle: "solid"
                },
                panelStyle3: {
                    height: "auto",
                    maxHeight: "150px",
                    borderWidth: "1px",
                    borderColor: "#ccc",
                    borderStyle: "solid"
                },
                banCiId: {
                    id: null
                },
                dateScope: {
                    otDate: new Date(),
                    startDate: new Date(),
                    endDate: new Date(),
                    beginHour: 0,
                    beginMinute: 0,
                    endHour: 0,
                    endMinute: 0,
                    //加班单是否为调休
                    isLeave: 0,
                    overTimeType: null,
                    overTimeTypeData: [],
                    isRepast: false,
                    isRepastDisabled: false,
                    //按班次录入
                    banCiType: null,
                    banCiTypeData: [],

                    //加班事由
                    reason: "",

                    //按时段录入
                    timeInterval: [],
                    //上传的文件名数组
                    uploadFileNames: []

                    //按时间录入
                },
                err: {
                    xqRowData: [],
                    xqColumnDefs: [
                        {headerName: "工号", field: "userNo", width: 100},
                        {headerName: "姓名", field: "userName", width: 100},
                        {headerName: "部门", field: "deptName", width: 200},
                        {headerName: "错误信息", field: "errorMsg", width: 500}
                    ]
                },
                /*时间选择收集*/
                timeSelectPattern: "1",
                timeFlag: true,
                banciSelectFlag: false,
            };
        },
        mounted() {
            tableBoxHeight();
            this.$refs.d1.close();
            this.$refs.errorXq.close();
            // 普通排班类型
            scheduleApi.getSchedulePuTong().then(res => {
                if (res.code == 200) {
                    this.dateScope.banCiTypeData = res.result;
                    //班次类型赋值
                    //this.dateScope.banCiType = res.result[0].id;
                } else {
                    this.$messager.alert({
                        title: "操作提示",
                        icon: "error",
                        msg: res.message
                    });
                }
            });
        },
        watch: {
            timeSelectPattern(val, oldVal) {
                this.timeSelectPatternFun(null)
            },
        },
        methods: {
            open() {
                // console.log(this.peopleData);
                this.$refs.d1.open();
            },
            close() {
                this.clearData();
                this.$refs.d1.close();
            },
            //保存加班
            async submitOverTime() {
                if (this.peopleData == [] || this.peopleData.length == 0 || this.peopleData == null) {
                    this.$messager.alert({
                        title: "操作提示",
                        icon: "warning",
                        msg: "账户未登录，请登录!"
                    });
                    return;
                }
                let otDate = moment(this.dateScope.otDate).format('YYYY-MM-DD');
                if (otDate == "" || otDate == "Invalid date" || otDate == null) {
                    this.$messager.alert({
                        title: "操作提示",
                        icon: "warning",
                        msg: "请选择加班日期!"
                    });
                    return;
                }
                let otList = []
                //手动录入
                if (this.timeSelectPattern == "1") {

                    if (
                        this.dateScope.beginHour == null ||
                        this.dateScope.beginMinute == null ||
                        this.dateScope.startDate == null
                    ) {
                        this.$messager.alert({
                            title: "操作提示",
                            icon: "warning",
                            msg: "请输入完整的开始时间!"
                        });
                        return;
                    }

                    if (
                        this.dateScope.endHour == null ||
                        this.dateScope.endMinute == null ||
                        this.dateScope.endDate == null
                    ) {
                        this.$messager.alert({
                            title: "操作提示",
                            icon: "warning",
                            msg: "请输入完整的结束时间!"
                        });
                        return;
                    }

                    let startDateTime
                        = moment(this.dateScope.startDate).hour(this.dateScope.beginHour).minute(this.dateScope.beginMinute);
                    let endDateTime
                        = moment(this.dateScope.endDate).hour(this.dateScope.endHour).minute(this.dateScope.endMinute);
                    let otBegin = startDateTime.diff(moment(moment(this.dateScope.otDate).format("YYYY-MM-DD")), 'minute')
                    let otEnd = endDateTime.diff(moment(moment(this.dateScope.otDate).format("YYYY-MM-DD")), 'minute')
                    if ((otEnd - otBegin) < 120) {
                        this.$messager.alert({
                            title: "操作提示",
                            icon: "warning",
                            msg: "加班结束时间必须大于加班开始时间,并且最小间隔为2小时！"
                        });
                        return;
                    }
                    if (this.dateScope.reason == "") {
                        this.$messager.alert({
                            title: "操作提示",
                            icon: "warning",
                            msg: "请填写加班事由!"
                        });
                        return;
                    }

                    //整理人员信息
                    let poepleInfo = {
                        //部门名称
                        deptName: this.peopleData[0].deptName,
                        //部门编号
                        deptSerial: this.peopleData[0].deptSerial,
                        //加班开始分钟(小时*60+分钟)
                        otBegin: otBegin,
                        //加班结束分钟(小时*60+分钟)
                        otEnd: otEnd,
                        //加班事由
                        reason: this.dateScope.reason,
                        //用户姓名
                        userName: this.peopleData[0].userName,
                        //用户工号
                        userNo: this.peopleData[0].userNo,
                        //用户编号
                        userSerial: this.peopleData[0].userSerial,
                        repastTime : 0
                    }
                    otList.push(poepleInfo)
                } else {
                    //按班次
                    if (this.dateScope.banCiType == "" || this.dateScope.banCiType == null) {
                        this.$messager.alert({
                            title: "操作提示",
                            icon: "warning",
                            msg: "请选择班次!"
                        });
                        return;
                    }
                    if (this.dateScope.reason == "") {
                        this.$messager.alert({
                            title: "操作提示",
                            icon: "warning",
                            msg: "请填写加班事由!"
                        });
                        return;
                    }
                    //整理人员信息
                    //根据登录人获取结合日历的相关数据
                    //整理请求的数据
                    let param = {
                        deptIds: null,
                        userIds: this.peopleData[0].userSerial,
                        actionDate: moment(this.dateScope.otDate).format("YYYY-MM-DD")
                    };
                    let res = await userApi.getUserCalendarInfoList(param)
                    if (res.code == "200") {
                        let selectUser = res.result.map(res => {
                            return {
                                userNo: res.userNo,
                                userName: res.userName,
                                userSerial: res.userSerial,
                                deptName: res.deptName,
                                deptSerial: res.deptSerial,
                                isRest: res.isRest
                            };
                        });

                        let userCalanderInfo = selectUser[0];
                        //根据当前日期是否是休息日，来确定时间取值
                        let otBegin = null;
                        let otEnd = null;
                        if (userCalanderInfo.isRest == 1) {
                            otBegin = this.dateScope.timeInterval.zzSbsj;
                            otEnd = this.dateScope.timeInterval.zwXbsj
                        } else {
                            otBegin = this.dateScope.timeInterval.sbsj;
                            otEnd = this.dateScope.timeInterval.xbsj
                        }
                        //整理人员信息
                        let poepleInfo = {
                            //部门名称
                            deptName: this.peopleData[0].deptName,
                            //部门编号
                            deptSerial: this.peopleData[0].deptSerial,
                            //加班开始分钟(小时*60+分钟)
                            otBegin: otBegin,
                            //加班结束分钟(小时*60+分钟)
                            otEnd: otEnd,
                            //加班事由
                            reason: this.dateScope.reason,
                            //用户姓名
                            userName: this.peopleData[0].userName,
                            //用户工号
                            userNo: this.peopleData[0].userNo,
                            //用户编号
                            userSerial: this.peopleData[0].userSerial,
                            //班次ID要带上
                            shiftId: this.dateScope.timeInterval.parent,
                            timeDuration :
                                dateUtil.toHourMinute(otEnd - otBegin-this.dateScope.timeInterval.repastTime),
                            repastTime : this.dateScope.timeInterval.repastTime
                        }
                        otList.push(poepleInfo)
                    } else {
                        this.$messager.alert({
                            title: "异常错误",
                            icon: "error",
                            msg: "加载数据失败!"
                        });
                    }
                }
                // 封装参数：文件名数组
                this.getUploadFileNames();
                let param = {
                    //加班日期
                    otDate: otDate,
                    //加班人员信息 JSON数组
                    otDetailDtoList: otList,
                    //上传文件的路径 字符串数组
                    uploadFileNames: this.dateScope.uploadFileNames,
                    //加班事由
                    reason: this.dateScope.reason,
                    //个人加班申请
                    applyType: '1'
                }
                // console.log(param)
                // return;
                this.$loading("请稍等...");
                // 添加加班
                overTimeApi.addOverTimeOrder(param).then(res => {
                    this.$loading.close();
                    if (res.code == 200) {
                        this.parentSearch();
                        this.close();
                        this.$messager.alert({
                            title: "系统提示",
                            icon: "success",
                            msg: "保存成功！"
                        });
                    } else {
                        if (res.result == null || res.result.length == 0) {
                            this.$messager.alert({
                                title: "系统提示",
                                icon: "error",
                                msg: res.message
                            });
                        } else {
                            //取错误信息集合的第一条，也仅仅应该只有一条
                            this.$messager.alert({
                                title: "系统提示",
                                icon: "error",
                                msg: res.result[0].errorMsg
                            });
                        }
                    }
                });
            }
            ,
            //录入成功 清除数据
            clearData() {
                this.dateScope.otDate = new Date();
                this.dateScope.isRepast = false;
                this.dateScope.beginHour = 0;
                this.dateScope.beginMinute = 0;
                this.dateScope.endHour = 0;
                this.dateScope.endMinute = 0;
                this.dateScope.reason = "";
                this.dateScope.startDate = new Date();
                this.dateScope.endDate = new Date();
                this.dateScope.banCiType = null; //this.dateScope.banCiTypeData[0].id;
                this.dateScope.overTimeType = null; //this.dateScope.overTimeTypeData[0].id;
            }
            ,

            //选择上传文件
            onFileSelect() {
            }
            ,
            // 选择加班日期
            selectionChangeOverTime() {
                this.timeSelectPatternFun(true)
            }
            ,
            /*切换取时间的方式*/
            timeSelectPatternFun(isSelectDate) {
                if (isSelectDate != null) {
                    this.dateScope.banCiType = null
                    this.dateScope.startDate = this.dateScope.otDate;
                    this.dateScope.beginHour = 0;
                    this.dateScope.beginMinute = 0;
                    this.dateScope.endDate = this.dateScope.otDate;
                    this.dateScope.endHour = 0;
                    this.dateScope.endMinute = 0;
                }
                {
                    if (this.timeSelectPattern == "1") {
                        //手动设置，即将选择的班次初始化，并禁用，日期选择放开
                        this.timeFlag = true
                        this.banciSelectFlag = false
                        //初始化
                        this.dateScope.banCiType = null
                        this.dateScope.startDate = this.dateScope.otDate;
                        this.dateScope.beginHour = 0;
                        this.dateScope.beginMinute = 0;
                        this.dateScope.endDate = this.dateScope.otDate;
                        this.dateScope.endHour = 0;
                        this.dateScope.endMinute = 0;
                    } else {
                        //根据班次，即启用下拉框，并禁用日期选择。
                        this.timeFlag = false
                        this.banciSelectFlag = true
                        //初始化
                        this.dateScope.startDate = this.dateScope.otDate;
                        this.dateScope.beginHour = 0;
                        this.dateScope.beginMinute = 0;
                        this.dateScope.endDate = this.dateScope.otDate;
                        this.dateScope.endHour = 0;
                        this.dateScope.endMinute = 0;
                    }


                }

            }
            ,
            //选择加班类型
            selectionChangeOverType(event) {
                let id = event.id;
                // console.log(id);
                if (id == 2 || id == 3) {
                    this.dateScope.isRepast = true;
                    this.dateScope.isRepastDisabled = true;
                } else {
                    this.dateScope.isRepast = false;
                    this.dateScope.isRepastDisabled = false;
                }
                if (this.dateScope.overTimeType != null && this.dateScope.banCiType != null) {
                    this.selectionChangeBanCi(this.banCiId);
                }
            }
            ,
            //选择班次 加载班次时段
            selectionChangeBanCi(event) {
                if (event == null) {
                    return false;
                }
                this.banCiId.id = event.id;
                // console.log(this.banCiId.id);
                timeIntervalApi
                    .getTimeIntervalListByParent({
                        parent: this.banCiId.id
                    })
                    .then(res => {
                        //处理班次时段
                        this.dateScope.timeInterval = res.result[0]
                    });
            }
            ,
            //整理上传文件名集合
            getUploadFileNames() {
                this.dateScope.uploadFileNames = [];
                let upload1 = this.$refs.upload1.getUploadFileName();
                this.addFileNames(upload1);
                let upload2 = this.$refs.upload2.getUploadFileName();
                this.addFileNames(upload2);
                let upload3 = this.$refs.upload3.getUploadFileName();
                this.addFileNames(upload3);
            }
            ,
            //添加上传文件名到集合
            addFileNames(name) {
                if (name != null) {
                    this.dateScope.uploadFileNames.push(name);
                }
            }
            ,
            validator(date) {
                {
                    if (date >= moment(this.dateScope.otDate).startOf('day').subtract(1, 'd') && date <=
                        moment(this.dateScope.otDate).startOf('day').add(1, 'd')) {
                        return true;
                    }
                    return false;
                }
            },
            otDateValidator(date) {
                if (date >=moment(new Date()).startOf("day").subtract(7, "d")) {
                    return true;
                }
                return false;
            },
        }
    }
    ;
</script>

<style scoped></style>
